<!--
 * @Author: your name
 * @Date: 2022-01-17 22:08:12
 * @LastEditTime: 2022-02-14 14:25:02
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-element-admin\src\views\crm\Linkman.vue
-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addShow()"
        >添加产品</el-button
      >
    </div>

    <TableGeneral
      :tableData="tableData"
      :tableColumn="tableColumn"
      :loading="tableLoading"
      :tableConfig="{ stripe: true }"
      @refresh="tableLoad"
      @search="search"
    >
      <div slot="status" slot-scope="{ scopeRow }">
        <el-tag v-show="scopeRow.status == 1" type="success"> 启用</el-tag>
        <el-tag v-show="scopeRow.status == 0" type="danger"> 禁用</el-tag>
      </div>

      <div slot="many_image" slot-scope="{ scopeRow }">
        <div style="display: flex; flex-wrap: wrap">
          <template v-if="scopeRow.many_image">
            <div
              v-for="(item, index) in scopeRow.many_image.split(',')"
              :key="index"
              style="width: 60px; margin-top: 5px"
            >
              <OneImage :imageUrl="imageUrl(item)" see />
            </div>
          </template>
        </div>
      </div>

      <div slot="convertible_assets" slot-scope="{ scopeRow }">
        <el-tag v-show="scopeRow.convertible_assets == 1"> 是</el-tag>
        <el-tag v-show="scopeRow.convertible_assets == 0" type="warning">
          否</el-tag
        >
      </div>
      <div slot="operation" slot-scope="{ scopeRow }">
        <el-button type="text" size="small" @click="edit(scopeRow)">
          编辑
        </el-button>

        <el-popconfirm
          title="确定要禁用吗"
          @confirm="editObj(scopeRow.id, { status: 0 })"
          v-show="scopeRow.status == 1"
        >
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >禁用</el-button
          >
        </el-popconfirm>
        <el-popconfirm
          title="确定要启用吗"
          @confirm="editObj(scopeRow.id, { status: 1 })"
          v-show="scopeRow.status == 0"
        >
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >启用</el-button
          >
        </el-popconfirm>
        <!-- <template> -->

        <el-popconfirm title="确定要删除吗" @confirm="delOne(scopeRow.id)">
          <!-- <div> -->
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >删除</el-button
          >
        </el-popconfirm>
      </div>
    </TableGeneral>

    <div class="pagination">
      <el-pagination
        background
        layout="sizes,total,prev, pager, next"
        :page-size="config.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="sizeChange"
        :total="tableCount"
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加联系人 -->
    <el-dialog
      :title="`${edit_id ? '编辑' : '添加'}产品`"
      :visible.sync="dialogFormVisible"
      @closed="closed"
    >
      <div class="dialogCenter">
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          v-loading="formLoading"
        >
          <el-form-item
            label="产品名称"
            :label-width="formLabelWidth"
            prop="product_name"
          >
            <el-input v-model="form.product_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="产品类型"
            :label-width="formLabelWidth"
            prop="product_type"
          >
            <el-input v-model="form.product_type" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item
            label="标准价格"
            :label-width="formLabelWidth"
            prop="standard_price"
          >
            <el-input
              v-model="form.standard_price"
              autocomplete="off"
              style="width: 200px"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="所属部门" :label-width="formLabelWidth">
            <!-- <el-input v-model="form.division_id" autocomplete="off"></el-input> -->
            <!-- {{Number(online_msg.division_id)}} -->
            <TreeSelct
              :props="{ value: 'id', label: 'name', children: 'children' }"
              :options="treeData"
              :accordion="true"
              :clearable="true"
              :value="division_id.toString()"
              :key="'TreeSelct' + division_id"
              ref="treeSelct"
              v-if="!treeDataLoading"
            />
          </el-form-item>
          <el-form-item
            label="可转资产"
            :label-width="formLabelWidth"
            prop="convertible_assets"
          >
            <el-select
              v-model="form.convertible_assets"
              placeholder="请选择是否可转资产"
              clearable
            >
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="销售单位"
            :label-width="formLabelWidth"
            prop="sales_status"
          >
            <el-input v-model="form.sales_status" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="产品图片" :label-width="formLabelWidth">
            <ManyImage
              :key="form.many_image"
              :imagesArray="form.many_image ? form.many_image.split(',') : []"
              path="crm/productImage"
              ref="manyImage"
            ></ManyImage>
          </el-form-item>

          <el-form-item
            label="状态"
            :label-width="formLabelWidth"
            prop="status"
          >
            <el-radio v-model="form.status" label="1">启用</el-radio>
            <el-radio v-model="form.status" label="0">禁用</el-radio>
          </el-form-item>

          <el-form-item
            label="产品描述"
            :label-width="formLabelWidth"
            prop="product_describe"
          >
            <el-input
              type="textarea"
              v-model="form.product_describe"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" v-loading="formLoading">
        <el-button @click="reset('form')" v-show="!edit_id">重置</el-button>

        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="`跟进情况`"
      :visible.sync="followUpObj.visible"
      width="70%"
    >
      <div class="dialogCenter">
        <ChangeableTable
          ref="changeableTable"
          :tableColumn="followUpObj.changeColumn"
          :loading="followUpObj.loading"
          :tableData="followUpObj.tableData"
        />
      </div>
      <div slot="footer" class="dialog-footer" v-loading="followUpObj.loading">
        <!-- <el-button @click="reset('form')">重置</el-button> -->

        <el-button type="primary" @click="ableSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const tableColumn = [
  {
    dataIndex: "id",
    width: "100",
    title: "ID",
    returnField: "like-crm_product-id",
  },
  {
    dataIndex: "product_name",
    width: "220",
    title: "产品名称",
    returnField: "like-crm_product-product_name",
  },
  {
    dataIndex: "product_type",
    width: "220",
    title: "产品类型",
    returnField: "like-crm_product-product_type",
  },
  {
    dataIndex: "division_name",
    width: "220",
    title: "所属部门",
    returnField: "like-chain-division_name",
  },
  {
    scopedSlots: "many_image",
    width: "220",
    title: "产品图片",
    noSearch: 1,
  },
  {
    scopedSlots: "status",
    width: "90",
    title: "状态",
    dataType: "select",
    selectOptions: [
      {
        title: "启用",
        value: 1,
      },
      {
        title: "禁用",
        value: 0,
      },
    ],
    returnField: "equal-crm_product-status",
  },
  {
    dataIndex: "standard_price",
    width: "220",
    title: "标准价格(元)",
    returnField: "like-crm_product-standard_price",
  },

  {
    dataIndex: "sales_status",
    width: "220",
    title: "销售单位",
    returnField: "like-crm_product-sales_status",
  },
  {
    scopedSlots: "convertible_assets",
    width: "80",
    title: "可转资产",
    dataType: "select",
    selectOptions: [
      {
        title: "是",
        value: 1,
      },
      {
        title: "否",
        value: 0,
      },
    ],
    returnField: "equal-crm_product-convertible_assets",
  },

  {
    dataIndex: "product_describe",
    width: "250",
    title: "产品描述",
    returnField: "like-crm_product-product_describe",
  },
  {
    scopedSlots: "operation",
    width: "180",
    title: "操作",
    position: "right",
    noSearch: 1,
  },
  // { dataIndex: "remark", width: "250", title: "备注" },
];

const formOriginal = () => {
  return {
    product_name: null,
    product_type: null,
    standard_price: null,
    convertible_assets: null,
    sales_status: null,
    product_describe: null,
    many_image: null,
    status: "1",
    division_id: null,
  };
};

const changeColumn = [
  {
    dataType: "textarea",
    title: "跟进日期",
    prop: "date",
    width: "200px",
  },
  {
    dataType: "textarea",
    title: "跟进人",
    prop: "name",
    width: "200px",
  },
  {
    dataType: "text",
    title: "跟进状态",
    prop: "state",
    width: "120px",
  },
  {
    dataType: "textarea",
    title: "跟进描述",
    prop: "describe",
  },
];

import TreeSelct from "@/components/TreeSelct";
import TableGeneral from "@/components/TableGeneral";
import ChangeableTable from "@/components/ChangeableTable";
import { mapActions, mapState } from "vuex";
import { validDecimal } from "@/utils/validate";
import ManyImage from "@/components/uploadImages/ManyImage";
import OneImage from "@/components/uploadImages/OneImage";
export default {
  name: "ComplexTable",
  components: {
    TreeSelct,
    TableGeneral,
    ChangeableTable,
    ManyImage,
    OneImage,
  },
   authorize:{
    'addShow':'添加',
    'edit':'编辑',
    'delOne':'删除',
    'editObj':'编辑'
  },
  data() {
    return {
      dialogFormVisible: false,
      form: formOriginal(),
      formLabelWidth: "120px",
      treeDataLoading: true,
      tableLoading: true,
      formLoading: false,
      division_id: 0,
      treeData: [],
      edit_id: 0,
      // linkmanBelong: {},
      config: {
        pageSize: 20,
        page: 1,
        keyWord: {},
      },
      rules: {
        product_name: [
          { required: true, message: "产品名称不为空", trigger: "blur" },
          { max: 255, message: "产品名称长度不超过255字符", trigger: "blur" },
        ],
        standard_price: [
          // { required: true, message: "产品名称不为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value == null || value == "" || validDecimal(value)) {
                callback();
              } else {
                callback(new Error("标准价格最多两位小数的数字"));
              }
            },
            trigger: "blur",
          },
        ],
      },
      tableData: [],
      tableColumn: tableColumn,
      tableCount: 0,
      // imagesArray: [],
      followUpObj: {
        visible: false,
        changeColumn: changeColumn,
        loading: false,
        tableData: [],
        target_id: "", //联系人id
        followUp_id: "", //沟通记录表id
      },
    };
  },
  created() {
    this.divisionListLoad();
    this.tableLoad();
    this.division_id = this.online_msg.division_id;
  },
  watch: {},
  computed: {
    ...mapState("user", ["online_msg"]),
  },

  methods: {
    ...mapActions("division", ["divisionList"]),
    // ...mapActions("followUp", [
    //   "crmFollowUpAdd",
    //   "crmFollowUpEdit",
    //   "crmFollowUpSelOne",
    // ]),
    // ...mapActions("linkman", [
    //   "linkmanAdd",
    //   "linkmanEdit",
    //   "linkmanList",
    //   "linkmanSelOne",
    // ]),
    ...mapActions("product", [
      "productAdd",
      "productEdit",
      "productList",
      "productSelOne",
    ]),
    ...mapActions("upload", ["manyFile"]),

    closed() {
      this.edit_id = "";
      this.form = formOriginal();
      this.division_id = this.online_msg.division_id;

      this.$refs.treeSelct.reset();
      this.$refs.form.clearValidate()

    },
    addShow() {
      // this.linkmanBelong = {
      //   nickName: this.online_msg.nickName,
      //   realName: this.online_msg.realName,
      // };
      this.dialogFormVisible = true;
    },
    reset(formName) {
      this.$refs[formName].resetFields();
      this.$refs.treeSelct.reset();
    },
    async tableLoad() {
      this.tableLoading = true;
      let res = await this.productList(
        // division_id: this.online_msg.division_id,
        this.config
      );
      if (res.code == 200) {
        const { list, total } = res.data;
        this.tableData = list;
        this.tableCount = total;
      }
      this.tableLoading = false;
    },
    search(e) {
      //  console.log(e)
      this.config.keyWord = e;
      this.tableLoad();
    },
    async edit(scopeRow) {
      this.dialogFormVisible = true;
      this.formLoading = true;
      this.edit_id = scopeRow.id;
      let res = await this.productSelOne({ id: scopeRow.id });
      if (res.code == 200) {
        Object.keys(this.form).forEach(
          (item) => (this.form[item] = res.data[item])
        );
        this.division_id = this.form.division_id;


        // this.linkmanBelong = {
        //   nickName: scopeRow.nickName,
        //   realName: scopeRow.realName,
        // };
          //12

        this.formLoading = false;
      }
    },
    async delOne(id) {
      this.tableLoading = true;
      let res = await this.productEdit({
        formData: { delete_time: this.sysTime() },
        conditions: { id: id },
      });
      if (res.code == 200) {
        this.$message.success("删除成功");
      }
      this.tableLoad();
    },
    async editObj(id, obj) {
      this.tableLoading = true;
      let res = await this.productEdit({
        formData: obj,
        conditions: { id: id },
      });
      if (res.code == 200) {
        this.$message.success("修改成功");
      }
      this.tableLoad();
    },

    
    
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm(
            "确定要" + (this.edit_id ? "编辑" : "添加") + "吗?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
      this.formLoading = true;

              let form = JSON.parse(JSON.stringify(this.form));
              form.division_id = this.$refs.treeSelct.valueId;
              var res = await this.$refs.manyImage.uploadApi();
              if (false !== res) {
                form.many_image = res;
              }
              if (this.edit_id) {
                res = await this.productEdit({
                  formData: form,
                  conditions: { id: this.edit_id },
                });
              } else {
                res = await this.productAdd({ formData: form });
              }

              if (res.code == 200) {
                this.$message.success(res.message);
                this.dialogFormVisible = false;
                this.tableLoad();
              }
      this.formLoading = false;

            })
            .catch(() => {});
        } else {
          // console.log('error submit!!');
          this.$message.error("信息填写错误");
          return false;
        }
      });
    },
    currentChange(e) {
      this.config.page = e;
      this.tableLoad();
    },
    sizeChange(e) {
      this.config.pageSize = e;
      this.tableLoad();
    },
    async divisionListLoad() {
      this.treeDataLoading = true;
      let res = await this.divisionList({ "equal-crm_division-status": 1 });
      if (res.code == 200) {
        // this.treeData[0] = { name: "全公司", id: 0, children: [] };
        this.treeData = res.data.list;
        this.treeDataLoading = false;
      }
    },
  },
};
</script>
<style scoped lang="less">
.dialogCenter {
  height: 60vh;
  overflow-y: scroll;
  padding: 10px;
}
.pagination {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
</style>
